from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from Core import models
from Core.exception import *
from Apis.response import Response
from Apis import auth

import json
import uuid


@csrf_exempt
def index(request):
    res = Response()
    res.output['url'] = request.path
    return res.ok("Hello World")


@csrf_exempt  # csrf 豁免
def login(request):
    response = Response()
    data = {
        "name": "",
        "pwd": ""
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))

        user = models.User()
        try:
            user = models.User.objects.get(name=data['name'])
        except user.DoesNotExist as e:
            return response.error("DoesNotExist", "User [{}] does not exist.".format(data['name']))

        if auth.pwd_encrypt(data['pwd']) != user.password:
            return response.error("PasswordError")

        session_id = uuid.uuid4().hex
        session_info = {
            'user_id': user.id,
            'user_name': data['name'],
            'last_login': str(timezone.now()),
            'ip': request.META.get('REMOTE_ADDR', ''),
            # 'META': request.META,
        }
        request.session[session_id] = session_info
        response.output['session_id'] = session_id
        response.output['session_info'] = session_info
        return response.ok('login success!')
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def logout(request):
    response = Response()
    data = {
        "session_id": "",
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))

        if data['session_id'] in request.session:
            session_info = request.session[data['session_id']]
            del request.session[data['session_id']]
            return response.ok("user [{}] has logged out.".
                               format(session_info['user_name']))
        else:
            return response.error("InvalidSessionID")
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def check_username(request):
    response = Response()
    data = {
        "name": "",
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.exception(NullRequest)
        data = json.loads(request.body.decode('utf-8'))
        if models.User.objects.filter(name=data['name']).count() > 0:
            return response.exception(UserNameExisted)
        else:
            return response.ok("username [{}] is available".format(data['name']))
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def register(request):
    response = Response()
    data = {
        "name": "",
        "pwd": "",
        "nickname": "",
        "mail": ""
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))

        # 检查用户名是否可用
        if models.User.objects.filter(name=data['name']).count() > 0:
            return response.error("UserNameIsExisted")

        try:
            user = models.User(
                name=data['name'],
                password=data['pwd'],
                nickname=data['nickname'],
                mail=data['mail'],
                register_date=timezone.now(),
            )
            user.save()
        except Exception as e:
            return response.error(str(e), "register error")
        else:
            return response.ok("register success!")
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def update(request):
    data = {
        "name": "",
        "pwd": "",
        "nickname": "",
        "mail": ""
    }
    response = Response()
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))

        user = models.User()
        try:
            user = models.User.objects.get(name=data['name'])
        except user.DoesNotExist as e:
            return response.error("DoesNotExist", "User [{}] does not exist.".format(data['name']))

        if auth.pwd_encrypt(data['pwd']) != user.password:
            return response.error("PasswordError")

        try:
            if 'nickname' in data: user.nickname = data['nickname']
            if 'mail' in data: user.mail = data['mail']
        except Exception as e:
            return response.error(str(e), "update user info failed.")

        return response.ok('update user [{}] info success!'.
                           format(user.name))
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())